import {Component, OnInit, Input} from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {GenerateTestService} from './generate-test.service';
import {QuestionListService} from '../question/list/list.service';

@Component({
  selector: 'app-generate-test',
  templateUrl: './generate-test.component.html',
  styleUrls: ['./generate-test.component.less'],
  providers: [GenerateTestService, QuestionListService]
})
export class GenerateTestComponent implements OnInit {
  validateForm: FormGroup;
  _id: string;

  /**
   * 表单模型对象
   * @type {{name: string; nickName: string; gender: string; age: string; phone: string; email: string; address: string}}
   */
  groups = [];
  options = [];

  formData = {
    username: '',
    password: '', // 面试人电话
    userkind: '',
    testcaselist: [
      {
        type: 0,
        number: 0,
      },
      {
        type: 1,
        number: 0
      },
      {
        type: 2,
        number: 0
      }
    ]
  };

  @Input()
  set id(value: string) {
    this._id = value;
  }

  constructor(private message: NzMessageService, private fb: FormBuilder, private generateTestservice: GenerateTestService, private questionListService: QuestionListService) {
    this.questionListService.getKindList().then((response: any[]) => {
      this.options = response;
    });
    this.groups = this.questionListService.getTypeList();
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required, Validators.pattern(/^1[34578]\d{9}$/)]],
      userkind: [null, [Validators.required]],
      classes: [null, [Validators.required]],
      class1: [null]
    });
  }

  /**
   * 表单提交方法
   * @private
   */
  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    if (this.validateForm.valid) {
      this.generateTestservice.create(this.formData)
        .then((result: Test) => {
          this.message.success('添加成功');
        });
    }
  }

  _cancel() {
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  _getCheckboxVal(value) {
    value.map(item => {
      this.formData.testcaselist.map(list => {
        if (list.type === parseInt(item.value)) {
          list.number = item.checked ? 1 : 0;
        }
      });
    });
  }

}

export class Test {
  key: string;
  value: string;
}
